<template>
  <div class="main-div">
    <div class="main-search-div">
      <el-form ref="searchRef"
               :model="state"
               status-icon
               inline>
        <el-form-item label="用户名" prop="username" class="main-search-item-4">
          <el-input v-model="state.username" type="text"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" class="main-search-item-4">
          <el-input v-model="state.phone" type="text"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="main-search-item-4">
          <el-input v-model="state.email" type="text"/>
        </el-form-item>
        <el-form-item label="是否停用" prop="isStop" class="main-search-item-4">
          <el-select v-model="state.isStop" placeholder="请选择" :clearable="true">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :loading="state.searchLoading">查询</el-button>
          <el-button @click="reset(searchRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-button-div">
      <el-button type="primary" @click="addUserFn">新增</el-button>
      <el-popconfirm title="是否启用?" @confirm="restartUserFn">
        <template #reference>
          <el-button type="primary">启用</el-button>
        </template>
      </el-popconfirm>
      <el-popconfirm title="是否停用?" @confirm="stopUserFn">
        <template #reference>
          <el-button type="danger">停用</el-button>
        </template>
      </el-popconfirm>
      <el-popconfirm title="是否重置?" @confirm="resetPasswordFn">
        <template #reference>
          <el-button type="default">重置密码</el-button>
        </template>
      </el-popconfirm>
      <el-popconfirm title="是否删除?" @confirm="delUserFn">
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>
    </div>
    <div class="main-table-div">
      <common-page-table
          :data="state.tableData"
          :columns="columns"
          :pagination="pagination"
          :show-border="true"
          :need-one-select="true"
          :show-no="true"
          :loading="state.tableLoading"
          :show-action="true"
          :action-config="actionConfig"
          @sizeChange="sizeChange"
          @currentChange="currentChange"
          @handle-current-change="handleTableCurrentChange">
        <template #action="{ row }">
            <el-button type="primary" size="small" round @click="detail(row)">详情</el-button>
            <el-button type="primary" size="small" round @click="edit(row)">编辑</el-button>
            <el-button type="warning" size="small" round @click="addRoleFn(row)">添加角色</el-button>
        </template>
      </common-page-table>
    </div>
  </div>

  <user-detail :show-dialog="userDetailParam.showDialog"
               :title="userDetailParam.title"
               :dialog-type="userDetailParam.dialogType"
               :detailParam="userDetailParam.detailParam"
               @open-dialog="openUserDetail"
               @init-dialog="initUserDetail"
               @close-dialog="closeUserDetail($event)"
               @closed-dialog="closedUserDetail($event)">
  </user-detail>
  <relation-transfer :show-dialog="relationTransfer.showDialog"
                     :title="relationTransfer.title"
                     :relation-id="relationTransfer.relationId"
                     :relation-type="relationTransfer.relationType"
                     @handleOpenDialog="openRelationTransfer"
                     @handleCloseDialog="closeRelationTransfer($event)"
                     @confirmRelation="handleConfirmRelation($event)"
  >
  </relation-transfer>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {
  delUserReq,
  getUserListReq,
  resetPasswordReq,
  restartUserReq,
  saveUserRoleIdsReq,
  stopUserReq
} from "@/api/admin/user.ts";
import CommonPageTable from "@/components/common/CommonPageTable.vue";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import UserDetail from "@/components/manager/user/UserDetail.vue";
import {DIALOG_ADD, DIALOG_EDIT, DIALOG_VIEW, RELATION_TYPE_USER} from "@/constants/common-constant.ts";
import RelationTransfer from "@/components/manager/relation/RelationTransfer.vue";

interface State {
  username: string;
  phone: string;
  email: string;
  isStop: string;
  tableData: any[];
  currentPage: number;
  pageSize: number;
  total: number;
  searchLoading: boolean;
  tableLoading: boolean;
}

const state = reactive<State>({
  username: '',
  phone: '',
  email: '',
  isStop: '',
  tableData: [],
  currentPage: 1,
  pageSize: 10,
  total: 0,
  searchLoading: false,
  tableLoading: false
})

interface UserDetailParam {
  showDialog: boolean;
  title: string;
  dialogType: string;
  detailParam: any;
}

const userDetailParam = reactive<UserDetailParam>({
  showDialog: false,
  title: '编辑',
  dialogType: 'edit',
  detailParam: {}
})

interface RelationTransfer {
  showDialog: boolean;
  title: string;
  relationId: string;
  relationType: string;
}

const relationTransfer = reactive<RelationTransfer>({
  showDialog: false,
  title: '',
  relationId: '',
  relationType: ''
})

const options = [
  {value: '0', label: '正常'},
  {value: '1', label: '停用'}
]

const columns = [
  {prop: 'username', label: '用户名', width: 'auto', fixed: 'left'},
  {prop: 'sexLabel', label: '性别', width: 'auto'},
  {prop: 'phone', label: '手机号', width: 'auto'},
  {prop: 'email', label: 'email', width: 'auto'},
  {prop: 'address', label: '地址', width: 'auto'},
  {prop: 'isStopLabel', label: '是否停用', width: 'auto'},
  {prop: 'createTime', label: '创建时间', width: 'auto'},
]

const pagination = {
  currentPage: state.currentPage,
  pageSize: state.pageSize,
  total: state.total
}

const actionConfig = {
  prop: 'action',
  label: '操作',
  width: '250px',
}

const currentSelectRow = ref();

const searchRef = ref<FormInstance>();

const search = async () => {
  // 查询统一跳转第一页
  state.currentPage = 1
  pagination.currentPage = 1

  searchList().then();
}

// 统一表格查询方法
const searchList = async () => {
  state.tableLoading = true
  state.searchLoading = true
  const params = {
    username: state.username,
    phone: state.phone,
    email: state.email,
    isStop: state.isStop,
    pageSize: state.pageSize,
    pageNum: state.currentPage
  }

  const res: any = await getUserListReq(params)
  state.searchLoading = false
  state.tableLoading = false
  if (res.code === RESPONSE_CODE_SUCCESS){
    state.tableData = res.data.rows
    state.total = res.data.total
    pagination.total = res.data.total
  } else {
    elMessageTip(res.tipType, res.message)
  }
}

const sizeChange = (val: number) => {
  state.pageSize = val;
  pagination.pageSize = val;

  searchList().then();
}

const currentChange = (val: number) => {
  state.currentPage = val;
  pagination.currentPage = val;

  searchList().then();
}

const edit = (row: any) => {
  userDetailParam.showDialog = true
  userDetailParam.title = '编辑'
  userDetailParam.dialogType = DIALOG_EDIT
  userDetailParam.detailParam = row
}

const detail = (row: any) => {
  userDetailParam.showDialog = true
  userDetailParam.title = '详情'
  userDetailParam.dialogType = DIALOG_VIEW
  userDetailParam.detailParam = row
}

const openUserDetail = () => {

}

const initUserDetail = () => {

}

const closeUserDetail = (val: boolean) => {
  userDetailParam.showDialog = val
}

const closedUserDetail = (obj: any) => {
  const dialogType = obj['dialogType']
  if (dialogType != DIALOG_VIEW) {
    searchList().then();
  }
  userDetailParam.showDialog = obj['showDialog']
}

const addUserFn = () => {
  userDetailParam.showDialog = true
  userDetailParam.title = '新增'
  userDetailParam.dialogType = DIALOG_ADD
  userDetailParam.detailParam = {}
}

const delUserFn = async () => {
  if (!currentSelectRow.value) {
    warningMessageTip("请选择要删除的用户");
    return
  }
  const userId = currentSelectRow.value['id'];
  const params = {
    id: userId
  }
  const res: any = await delUserReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    searchList().then();
  }
}

const stopUserFn = async () => {
  if (!currentSelectRow.value) {
    warningMessageTip("请选择要停用的用户");
    return
  }

  const userId = currentSelectRow.value['id'];
  const params = {
    id: userId
  }
  const res: any = await stopUserReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    searchList().then();
  }
}

const restartUserFn = async () => {
  if (!currentSelectRow.value) {
    warningMessageTip("请选择要启用的用户");
    return
  }

  const userId = currentSelectRow.value['id'];
  const params = {
    id: userId
  }
  const res: any = await restartUserReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    searchList().then();
  }
}

const resetPasswordFn = async () => {
  if (!currentSelectRow.value) {
    warningMessageTip("请选择要重置密码的用户");
    return
  }

  const userId = currentSelectRow.value['id'];
  const params = {
    id: userId
  }
  const res: any = await resetPasswordReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    searchList().then();
  }
}

const handleTableCurrentChange = (row: any) => {
  currentSelectRow.value = row
}

const addRoleFn = (row: any) => {
  relationTransfer.showDialog = true;
  relationTransfer.title = row.username + '角色分配';
  relationTransfer.relationId = row.id;
  relationTransfer.relationType = RELATION_TYPE_USER
}

const openRelationTransfer = () => {

}

const closeRelationTransfer = (val: boolean) => {
  relationTransfer.showDialog = val
}

const handleConfirmRelation = async (data: any) => {
  const params = {
    id: data.relationId,
    roleList: data.selectInfo
  }
  const res: any = await saveUserRoleIdsReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    relationTransfer.showDialog = false
  }
}

onMounted(() => {
  searchList().then();
})

const reset = (formEl: FormInstance | undefined) => {
  formEl?.resetFields();
}
</script>

<style scoped>

</style>